// 下载小程序二维码的工具js
import request from 'request';
import sign from './wxSign';
import redis from '../redis';
import { qiniuUpload } from '../qiniuUpload';
import { getWxAccountToken, getWxappToken } from './token';

export async function requestWxCode(shareId) {
  const token = await getWxappToken();
  return new Promise((resolve, reject) => {
    // 请求方式以及参数说明见https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html
    request(
      {
        method: 'POST',
        url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token,
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify({
          // 传入shareId作为sence值
          scene: shareId,
          path: 'pages/loading/loading',
          width: 430,
          auto_color: false,
          line_color: { r: '0', g: '0', b: '0' },
          is_hyaline: false
        }),
        encoding: null
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + token);
          console.log('接口请求参数', {
            scene: shareId,
            path: 'pages/loading/loading',
            width: 430,
            auto_color: false,
            line_color: { r: '0', g: '0', b: '0' },
            is_hyaline: false
          });
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        const image = Buffer.from(body, 'binary');
        // 上传到七牛云
        qiniuUpload
          .upload(image, 'mbook/share/' + shareId + '.jpeg')
          .then(result => {
            resolve(result.url);
          })
          .catch(error => {
            console.log('图片上传七牛云失败', error);
            reject(error);
          });
      }
    );
  });
}

// 获取ticket
export async function getTicket() {
  // 查看redis中是否存在token值
  const wxTicketInRedis = await redis.get('wxTicket');
  if (wxTicketInRedis) {
    return wxTicketInRedis;
  } else {
    let newTicket = await requestWxTicket();
    console.log(newTicket);
    if (typeof newTicket === 'string') {
      newTicket = JSON.parse(newTicket);
    }
    if (newTicket.ticket) {
      // 存储新的token
      redis.set('wxToken', newTicket.ticket, 'EX', 2 * 60 * 60);
      return newTicket.ticket;
    } else {
      console.log('获取ticket失败');
      return '';
    }
  }
}

// 获取网页跳转的微信ticket
export async function requestWxTicket() {
  const token = await getWxappToken(true);
  return new Promise((resolve, reject) => {
    // 请求方式以及参数说明见https://developers.weixin.qq.com/miniprogram/dev/api/qrcode.html
    request(
      {
        method: 'POST',
        url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token + '&type=jsapi',
        headers: {
          'Content-type': 'application/json'
        }
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token + '&type=jsapi');
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        resolve(body);
      }
    );
  });
}

// 签名
export async function signTicket() {
  const ticket = await getTicket();
  const url = 'https://game.weixin.qq.com/cgi-bin/h5/static/community/club_detail.html?jsapi=1&banner_need=1&uin=&key=&appid=wx35a4657522d31151&topic_id=37467564&ssid=7&is_self=1&cluster_id=&is_article=&_a=1#wechat_redirect';
  return sign(ticket, url);
}

/**
 * 获取网页打开小程序的网址
 */
export async function getWxOpenSchema({ page = '/pages/index/index', query = '' }) {
  const token = await getWxAccountToken(true);
  return new Promise((resolve, reject) => {
    // 请求方式以及参数说明见https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html
    request(
      {
        method: 'POST',
        url: 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' + token + '&type=jsapi',
        json: true,
        body: {
          access_token: token,
          jump_wxa: {
            path: page,
            query
          },
          is_expire: true,
          expire_type: 1,
          expire_interval: 7
        },
        headers: {
          'Content-type': 'application/json'
        }
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' + token + '&type=jsapi');
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        resolve(body);
      }
    );
  });
}
